package com.wang.springbootinit.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wang.springbootinit.common.ErrorCode;
import com.wang.springbootinit.exception.BusinessException;
import com.wang.springbootinit.mapper.HonorMapper;
import com.wang.springbootinit.model.entity.Honor;
import com.wang.springbootinit.model.entity.Student;
import com.wang.springbootinit.model.entity.User;
import com.wang.springbootinit.model.param.HonorParam;
import com.wang.springbootinit.model.vo.HonorVO;
import com.wang.springbootinit.service.HonorService;
import com.wang.springbootinit.service.StudentService;
import com.wang.springbootinit.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toMap;

/**
 * 荣誉服务实现类
 * 实现荣誉相关的业务逻辑，包括荣誉的申请、审核等功能
 */
@Service
public class HonorServiceImpl extends ServiceImpl<HonorMapper, Honor> implements HonorService {

    @Resource
    private HonorMapper honorMapper;
    
    @Resource
    private UserService userService;

    @Resource
    private StudentService studentService;

    /**
     * 添加荣誉
     * 创建新的荣誉记录，设置初始状态为待审核
     *
     * @param param 荣誉信息
     * @return 新创建的荣誉ID
     */
    @Override
    public Long addHonor(HonorParam param) {
        // 参数校验
        if (param == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (StringUtils.isAnyBlank(param.getName(), param.getLevel(), param.getIssuer())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "荣誉信息不完整");
        }

        String studentNum = param.getStudentNum();
        if(ObjectUtil.isNull(studentNum)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Student student = studentService.getStudentByNumber(studentNum);
        if(ObjectUtil.isNull(student)){
            throw new BusinessException(ErrorCode.STUDENT_NOT_EXIST);
        }

        Honor honor = new Honor();
        BeanUtils.copyProperties(param,honor);
        honor.setStudentId(student.getId());

        // 设置初始状态和时间
        Date now = new Date();
        honor.setStatus(0); // 待审核状态
        if(ObjectUtil.isNull(honor.getApplyTime())){
            honor.setApplyTime(now);
        }
        honor.setCreateTime(now);
        honor.setUpdateTime(now);
        
        // 保存荣誉信息
        honorMapper.insert(honor);
        return honor.getId();
    }

    /**
     * 获取荣誉详情
     * 根据ID查询荣誉信息
     *
     * @param id 荣誉ID
     * @return 荣誉详情
     */
    @Override
    public Honor getHonorById(Long id) {
        if (id == null || id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        return honorMapper.selectById(id);
    }

    /**
     * 获取学生的荣誉列表
     * 查询指定学生的荣誉记录
     *
     * @param studentId 学生ID
     * @param status 审核状态（可选）
     * @return 荣誉列表
     */
    @Override
    public List<Honor> getStudentHonors(Long studentId, Integer status) {
        if (studentId == null || studentId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        
        QueryWrapper<Honor> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("student_id", studentId);
        if (status != null) {
            queryWrapper.eq("status", status);
        }
        queryWrapper.orderByDesc("create_time");
        
        return honorMapper.selectList(queryWrapper);
    }

    /**
     * 分页获取荣誉列表
     * 支持按条件筛选
     *
     * @param current 当前页码
     * @param pageSize 每页大小
     * @param studentNumber 学生ID（可选）
     * @param level 荣誉级别（可选）
     * @param status 审核状态（可选）
     * @return 分页结果
     */
    @Override
    public Page<HonorVO> listHonors(long current, long pageSize, String studentNumber, String level, Integer status) {
        // 创建查询条件
        QueryWrapper<Honor> queryWrapper = new QueryWrapper<>();

        if(StrUtil.isNotEmpty(studentNumber)){
            Student student = studentService.getStudentByNumber(studentNumber);
            // 添加筛选条件
            queryWrapper.eq("studentId", student.getId());
        }

        if (StringUtils.isNotBlank(level)) {
            queryWrapper.eq("level", level);
        }
        if (status != null) {
            queryWrapper.eq("status", status);
        }
        
        // 按创建时间降序排序
        queryWrapper.orderByDesc("createTime");
        
        // 分页查询
        Page<Honor> page = new Page<>(current, pageSize);
        Page<Honor> honorPage = honorMapper.selectPage(page, queryWrapper);

        // 转换为VO
        List<Honor> records = honorPage.getRecords();
        if(CollUtil.isEmpty(records)){
            return new Page<>();
        }
        List<Long> studentIds = records.stream().map(Honor::getStudentId).collect(Collectors.toList());
        List<Student> students = studentService.listByIds(studentIds);
        if(CollUtil.isEmpty(students)){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        Map<Long, Student> studentMap = students.stream().collect(toMap(Student::getId, Function.identity(), (k1, k2) -> k1));
        List<HonorVO> honorVOList = records.stream().map(honor -> {
            HonorVO honorVO = new HonorVO();
            BeanUtils.copyProperties(honor, honorVO);
            Student student = studentMap.get(honorVO.getStudentId());
            honorVO.setStudentName(student.getName());
            honorVO.setStudentNumber(student.getStudentNumber());
            return honorVO;
        }).collect(Collectors.toList());

        Page<HonorVO> res = new Page<>();
        res.setTotal(honorPage.getTotal());
        res.setRecords(honorVOList);
        res.setCurrent(honorPage.getCurrent());
        res.setSize(honorPage.getSize());
        return res;
    }

    /**
     * 审核荣誉
     * 更新荣誉的审核状态和审核意见
     *
     * @param honor 包含审核结果的荣誉信息
     * @param request HTTP请求对象，用于获取当前审核人信息
     * @return 是否审核成功
     */
    @Override
    public boolean auditHonor(Honor honor, HttpServletRequest request) {
        // 参数校验
        if (honor == null || honor.getId() == null || honor.getStatus() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        
        // 获取当前登录用户作为审核人
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        
        // 获取原荣誉信息
        Honor oldHonor = honorMapper.selectById(honor.getId());
        if (oldHonor == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        
        // 只能审核待审核状态的荣誉
        if (oldHonor.getStatus() != 0) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "该荣誉已审核");
        }
        
        // 更新审核信息
        Date now = new Date();
        oldHonor.setStatus(honor.getStatus());
        oldHonor.setAuditOpinion(honor.getAuditOpinion());
        oldHonor.setAuditor(loginUser.getUserName());
        oldHonor.setAuditTime(now);
        oldHonor.setUpdateTime(now);
        
        return honorMapper.updateById(oldHonor) > 0;
    }

    /**
     * 统计各级别荣誉数量
     * 统计不同级别荣誉的获得数量
     *
     * @param studentId 学生ID（可选）
     * @return 统计结果
     */
    @Override
    public List<Honor> getHonorStatistics(Long studentId) {
        return honorMapper.getHonorStatistics(studentId);
    }

    /**
     * 获取学生参加的荣誉
     * @param request
     * @return
     */
    @Override
    public List<HonorVO> listHonors(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        Long studentId = loginUser.getStudentId();

        if(ObjectUtil.isNull(studentId)){
            throw new BusinessException(ErrorCode.ACCOUNT_DOES_NOT_EXIST);
        }
        Student student = studentService.getStudentById(studentId);
        if(ObjectUtil.isNull(student)){
            throw new BusinessException(ErrorCode.ACCOUNT_DOES_NOT_EXIST);
        }

        LambdaQueryWrapper<Honor> queryWrapper = new LambdaQueryWrapper<Honor>()
                .eq(Honor::getStudentId, studentId)
                .orderByDesc(Honor::getCreateTime);

        List<Honor> honors = list(queryWrapper);
        return honors.stream().map(honor -> {
            HonorVO honorVO = new HonorVO();
            BeanUtils.copyProperties(honor, honorVO);
            honorVO.setStudentName(student.getName());
            honorVO.setStudentNumber(student.getStudentNumber());
            return honorVO;
        }).collect(Collectors.toList());
    }

    /**
     * 学生申请
     * @param honor
     * @param request
     * @return
     */
    @Override
    public Boolean currentStudentApply(Honor honor, HttpServletRequest request) {
        // 参数校验
        if (honor == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 获取当前登录用户作为审核人
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        Long studentId = loginUser.getStudentId();

        if(ObjectUtil.isNull(studentId)){
            throw new BusinessException(ErrorCode.ACCOUNT_DOES_NOT_EXIST);
        }
        Student student = studentService.getStudentById(studentId);
        if(ObjectUtil.isNull(student)){
            throw new BusinessException(ErrorCode.ACCOUNT_DOES_NOT_EXIST);
        }
        honor.setStudentId(student.getId());
        save(honor);
        return true;
    }
} 